#!/bin/bash
#
# addNode 安装脚本 2016-08-22
#

test -z "$*" && \
	echo 'ERROR! addNode.sh 必要参数不能为空！参数要求: nodeIp1 nodeIp2...(以” “分割)' \
    && exit -1;
cd $(cd `dirname $0`; pwd)
echo "begin to setup node : $*"
sh printLine.sh '='
echo "pwd: " `pwd`
# test files
for file in sshkeygen.sh setup-node.sh addRoute.sh doAddRoute.sh getPubKey.sh
do
	test ! -f $file && echo "$file not found." && exit -1
done

paramNodes=$*
# push public key 
sh sshkeygen.sh $paramNodes
if [[ $? -ne 0 ]]; then
	echo "Error!"
	sh printLine.sh 'x'
	exit -1
fi
#get master ip
masterIp=`ip a | grep inet | grep -v inet6 | grep -v 127.0.0.1|grep brd|awk '{print $2}'|awk -F '/' '{print $1}'`
echo "master IP is : $masterIp"
test -z "$masterIp" && \
    echo "addNode.sh masterIp get error!" \
    && exit -1;
#get registry ip
#sh getDockerRegistry.sh
#dockerRegistry=`cat /usr/local/etc/registry`
#if [[ -z "$dockerRegistry" ]]; then
#	echo "Error! dockerRegistry setup error."
#	sh printLine.sh 'x'
#	exit -1;
#fi


# 执行node安装脚本


declare -A map=()
for nodeIp in $paramNodes
do
	echo "begin install node $nodeIp.."
	sh printLine.sh
	scp setup-node.sh root@$nodeIp:~/
	ssh root@$nodeIp "sh ~/setup-node.sh $masterIp"
	if [[ $? -ne 0 ]]; then
		sh printLine.sh 'x'
		map["$nodeIp"]='no'
	else
		map["$nodeIp"]='yes'
	fi
done
# 检测node注册
for node in $paramNodes
do
	if [[ ${map["$nodeIp"]} = 'no' ]]; then
		echo "$nodeIp install failed. continue"
		continue;
	fi
	# 等待node注册
	for (( i = 0; i < 10; i++ )); do
		test $i -eq 9 && echo "Error! $node registered failed." && break;
		thisAddedNode=`kubectl get node | grep $node`
		if [[ -z "$thisAddedNode" ]]; then
			sleep 5 && echo "$node registering.."
		else
			echo "$node registered."
			break;
		fi
		
	done
done

# 添加lables属性
addedNodes=$(kubectl get node|grep -v 'NAME'|awk '{print $1}')
for node in $addedNodes
do
	echo "add lables to $node..."
	kubectl label --overwrite nodes $node node=$node
done
# 添加路由表
sh addRoute.sh
echo "setup node end."
sh printLine.sh